package com.tc.objectstream;



import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;

/**
 * @Auther: tianchao
 * @Date: 2021/11/25 16:25
 * @Description:
 */
public class Copy {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student student = new Student();
        student.setAge(14);
        student.setHigh(170);
        Student left = new Student();
        left.setAge(16);
        left.setHigh(180);
        student.setLeft(left);
        Student copy = copy(student);
        System.out.println(copy);
    }
    public static <T extends Serializable> T copy(T obj)  {
        T clone = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteOutputStream byteOutputStream = new ByteOutputStream();
            oos = new ObjectOutputStream(byteOutputStream);
            oos.writeObject(obj);
            //分配内存 写入原始对象，生成新对象
            ByteArrayInputStream ios = new ByteArrayInputStream(byteOutputStream.toByteArray());
            ois = new ObjectInputStream(ios);
            clone = (T)ois.readObject();
            ois.close();
        }catch (IOException ioe){
            ioe.printStackTrace();
        }catch (ClassNotFoundException ce){
            ce.printStackTrace();
        }finally {
            try {
                if (oos!=null) {
                    oos.close();
                }
                if (ois!=null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return clone;
    }
}
